﻿using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Forms;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using ContractManager.BLL.Business;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;

namespace ContractManager.Lists.Contracts
{
    public partial class FrmRevenues : XtraFormBase
    {
        #region "Define Variable"
        private readonly BackgroundWorker _loadworker = new BackgroundWorker();
        private int _invId;
        private int _formNo;
        private DateTime _currentDate;
        #endregion

        #region "Form Construction"
        public FrmRevenues()
        {
            InitializeComponent();
            InitializeControls();
            ClsVariable.DoubleBuffer(this);
            _loadworker.DoWork += loadworker_DoWork;
            _loadworker.RunWorkerCompleted += loadworker_RunWorkerCompleted;
        }
        #endregion

        #region "Private Method"
        
        private void CheckPer()
        {
            var item = ClsForms.SelectByUserForm(ClsVariable.RoleNo, FormNo);
            if (item == null) return;
            AllowAdd = item.AllowAdd;
            AllowDelete = item.AllowDelete;
            AllowEdit = item.AllowEdit;
            AllowAccess = item.AllowAccess;
            AllowPrint = item.AllowPrint;
            this.LstLockDate = ClsVoucherLock.GetLockByFormNo(FormNo);
            
        }

        private void LockMenu(bool mnlock)
        {
            bool condition = ClsVariable.IsEditVoucher;
            btnNew.Enabled = AllowAdd;
            btnEdit.Enabled = !mnlock && AllowEdit && condition && LstLockDate.Contains(_currentDate) == false;
            btnDelete.Enabled = !mnlock && AllowDelete && condition && LstLockDate.Contains(_currentDate) == false;
            btnView.Enabled = !mnlock && AllowAccess;
            btnPrint.Enabled = AllowPrint;
        }

        void InitializeControls()
        {
            bdsMain.DataSource = typeof(Entity.Capitals);
            grdRevenues.DataSource = bdsMain;
            grdRevenues.UseEmbeddedNavigator = true;
            grvRevenues.OptionsBehavior.Editable = false;
        }

        public void GetData()
        {
            if (!_loadworker.IsBusy)
            {
                //grdInvestors.DataSource = null;
                _loadworker.RunWorkerAsync();
                ClsVariable.SetWaitDialogCaption(string.Format("Nạp danh sách {0}...", Text));
            }
        }

        private void DoNew()
        {
            var frm = new FrmRevenuesDetail
                {
                MasterId = 0,
                AsSysBillStyleId = ClsVariable.AsSysBillStyleId,
                AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                AsPerPersonId = ClsVariable.EmployeeId,
                FormNo = _formNo,

                FormSysBillStyleIdExport = FormSysBillStyleIdExport,
                FormXtraLayoutTemplate = FormXtraLayoutTemplate,
                FormXtraGridLayoutTemplate = FormXtraGridLayoutTemplate,
                FormReportLayoutTemplate = FormReportLayoutTemplate,
                FormDetailVatGridLayout = this.FormDetailVatGridLayout,
                VoucherCate = this.VoucherCate,
                IsPrintAfterSave = this.FormIsPrintAfterSave,
                FormAccountDefault = this.FormAccountDefault,
                FormIsNotValidate = this.FormIsNotValidate,
                Text = String.Format("Thông tin {0}", this.Text),
                LstLockDate = this.LstLockDate,
                
                AllowDelete = this.AllowDelete,

                MdiParent = this.MdiParent,
                WindowState = FormWindowState.Maximized
            };
            frm.Closed += FrmOnClosed;
            frm.Show();
            frm.Focus();
        }

        private void DoEdit()
        {
            _invId = Convert.ToInt32(grvRevenues.GetRowCellValue(grvRevenues.FocusedRowHandle, FieldNameId));
            var frm = new FrmRevenuesDetail
                {
                MasterId = _invId,
                AsSysBillStyleId = ClsVariable.AsSysBillStyleId,
                AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                AsPerPersonId = ClsVariable.EmployeeId,
                FormNo = _formNo,
                FormSysBillStyleIdExport = FormSysBillStyleIdExport,
                FormXtraLayoutTemplate = FormXtraLayoutTemplate,
                FormXtraGridLayoutTemplate = FormXtraGridLayoutTemplate,
                FormReportLayoutTemplate = FormReportLayoutTemplate,
                FormDetailVatGridLayout = this.FormDetailVatGridLayout,
               
                VoucherCate = this.VoucherCate,
                IsPrintAfterSave = this.FormIsPrintAfterSave,
                FormAccountDefault = this.FormAccountDefault,
                FormIsNotValidate = this.FormIsNotValidate,
                LstLockDate = this.LstLockDate,
                AllowDelete = this.AllowDelete,
                Text = String.Format("Thông tin {0}", this.Text),
                MdiParent = this.MdiParent,
                
                WindowState = FormWindowState.Maximized
            };
            frm.Closed += FrmOnClosed;
            frm.Show();
            frm.Focus();
        }

        private void DoView()
        {
            _invId = Convert.ToInt32(grvRevenues.GetRowCellValue(grvRevenues.FocusedRowHandle, FieldNameId));
            var frm = new FrmRevenuesDetail
                {
                MasterId = _invId,
                AsSysBillStyleId = ClsVariable.AsSysBillStyleId,
                AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                AsPerPersonId = ClsVariable.EmployeeId,
                FormNo = _formNo,
                OnlyView = true,

                FormSysBillStyleIdExport = FormSysBillStyleIdExport,
                FormXtraLayoutTemplate = FormXtraLayoutTemplate,
                FormXtraGridLayoutTemplate = FormXtraGridLayoutTemplate,
                FormReportLayoutTemplate = FormReportLayoutTemplate,
                FormDetailVatGridLayout = this.FormDetailVatGridLayout,

                VoucherCate = this.VoucherCate,
                IsPrintAfterSave = this.FormIsPrintAfterSave,
                FormAccountDefault = this.FormAccountDefault,
                FormIsNotValidate = this.FormIsNotValidate,

                Text = String.Format("Thông tin {0}", this.Text),
                MdiParent = this.MdiParent,
                
                WindowState = FormWindowState.Maximized
            };

            frm.Show();
            frm.Focus();
        }

        private void FrmOnClosed(object sender, EventArgs eventArgs)
        {
            var frmForm = sender as FrmRevenuesDetail;
            if (frmForm != null && frmForm.SaveClose)
            {
                GetData();
            }
        }

        private void DoDelete()
        {
            _invId = Convert.ToInt32(grvRevenues.GetRowCellValue(grvRevenues.FocusedRowHandle, FieldNameId));
            string strMasterId = _invId.ToString(CultureInfo.InvariantCulture);
            if (strMasterId.Length== 0) return;
            try
            {
                if (
                        XtraMessageBox.Show(
                                        "Bạn có muốn xoá bản ghi hiện tại không?",
                                        "Thông báo",
                                        MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Question) == DialogResult.No) return;
                ClsRevenues.DeleteByPk(Convert.ToInt32(strMasterId));
                grvRevenues.DeleteRow(grvRevenues.FocusedRowHandle);
                XtraMessageBox.Show(
                      "Bản ghi đã được xoá. ",
                      "Thông báo",
                      MessageBoxButtons.OK,
                      MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                       "Có lỗi xảy ra trong quá trình xóa dữ liệu. " + ex.Message,
                       "Thông báo",
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Error);
            }
        }

        private void DoPrint()
        {
            grdRevenues.ShowPrintPreview();
        }
        #endregion

        #region "Background Worker"

        private void loadworker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var list = ClsRevenues.GetAll(this.FormNo, this.VoucherCate, txtPeriod.FromDate, txtPeriod.ToDate);
                e.Result = list;
            }
            catch (Exception)
            {
                e.Cancel = true;
            }
        }

        private void loadworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Action a = () =>
            {
                bdsMain.DataSource = e.Result;
            };
            grdRevenues.Invoke(a);
            ClsVariable.SetWaitDialogCaption(string.Format("Danh sách {0} đã được nạp", Text));
        }
        #endregion

        #region "Form Event"
        private void FrmRevenuesLoad(object sender, EventArgs e)
        {
            if (Tag != null)
            {
                repositoryItemPopupContainerEdit.PopupControl = popupContainerControl;
                txtPeriod.Year = ClsVariable.Year;
                txtPeriod.SelectIndex = 3;
                _formNo = Convert.ToInt32(Tag);
                ClsVariable.CreateWaitDialog(ClsVariable.StrCaption, "Vui lòng đợi...");
                ClsVariable.SetWaitDialogCaption("Kiểm tra dữ liệu phân quyền...");
                CheckPer();
                ClsVariable.SetWaitDialogCaption(string.Format("Nạp danh sách {0}...", this.Text));
                GetData();
                ClsVariable.CloseWaitDialog();
                FieldNameId = "RevId";
                LockMenu(true);
                grvRevenues.FocusedRowHandle = GridControl.AutoFilterRowHandle;
                if (!String.IsNullOrEmpty(FormReportLayoutTemplate))
                {
                    string filePath = ClsVariable.GetRestoreLayoutFullPath(FormReportLayoutTemplate);
                    grvRevenues.RestoreLayoutFromXml(filePath, DevExpress.Utils.OptionsLayoutBase.FullLayout);
                }
                if (!String.IsNullOrEmpty(FormXtraGridSearchLayout))
                {
                    var filePath = ClsVariable.GetRestoreLayoutFullPath(FormXtraGridSearchLayout);
                    grvDetail.RestoreLayoutFromXml(filePath, DevExpress.Utils.OptionsLayoutBase.FullLayout);
                }
               
            }

        }

        #endregion

        #region "Toolbar Event"
        private void TbMenuItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "btnNew":
                    DoNew();
                    break;
                case "btnEdit":
                    DoEdit();
                    break;
                case "btnView"://Xem thông tin chứng từ
                    DoView();
                    break;
                case "btnDelete":
                    DoDelete();
                    break;
                case "btnRefresh"://Nạp lại dữ liệu
                    GetData();
                    break;
                case "btnPrint"://In phiếu
                    DoPrint();
                    break;
                case "btnDesignMasterGrid":
                    ClsVariable.ShowDesignXtraGrid(grdRevenues);
                    break;
                case "btnDesignDetailGrid":
                    ClsVariable.ShowDesignXtraGrid(grdDetail);
                    break;
                case "btnClose":
                    Close();
                    break;
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            GetData();
        }
        #endregion

        #region "Grid Event"
        private void grvRevenues_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0)
            {
                _invId = 0;
                grdDetail.DataSource = null;
                LockMenu(true);
                return;
            }
            if (grvRevenues.GetRowCellValue(e.FocusedRowHandle, FieldNameId) != DBNull.Value)
            {
                _invId = Convert.ToInt32(grvRevenues.GetRowCellValue(e.FocusedRowHandle, FieldNameId));
                _currentDate =
                    Convert.ToDateTime(grvRevenues.GetRowCellValue(e.FocusedRowHandle, "RevDate")).Date;
                grdDetail.DataSource = null;grdDetail.DataSource = ClsRevenues.ListDetail(_invId);
                LockMenu(false);
            }
        }
        #endregion

       

    }
}
